<?php

namespace App\Services\Assess;

use App\Models\Assess\EvaluationMonitorConnectModel;
use App\Models\Assess\EvaluationMonitoringModel;
use App\Models\Assess\OrderAndCustomersOrderDetailModel;
use App\Models\Assess\OrderAndCustomersOrderModel;
use App\Models\Register\ActivateUserManagementModel;
use App\Models\UserModel;
use App\Services\BaseService;
use App\Services\Common\CommonService;
use App\Services\Common\RedisService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class EvaluationMonitoringService extends BaseService
{

    //标签用途(1:激活买家管理,2:其他)
    public $tagType = [
        1 => '订单与客户',
        2 => '通用'
    ];

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new EvaluationMonitoringModel();
    }


    public function getList()
    {
        $param = request()->all();
        // 查询条件
        $map[] = ['mark','=',1];
        $account = getter($param, 'account', '');
        $country = getter($param, 'country', '');
        $asin = getter($param, 'asin', '');
        $tagName = getter($param, 'tag_name', '');
        $tagType = getter($param, 'tag_type', 0);
        $createUser = getter($param, 'create_user', 0);
        $sort = getter($param, 'sort', 'create_time');
        $order = getter($param, 'order', 'desc');
        $time = getter($param, 'time', []);
        $page_size = getter($param, 'page', 1);
        $limit = getter($param, 'limit', 10);

        if (!empty($account)) $map[] = ['account', '=', $account];
        if (!empty($country)) $map[] = ['country', '=', $country];
        if (!empty($asin)) $map[] = ['asin', '=', $asin];

        if (!empty($time)) {
            if (!empty($time[0])) $map[] = ['create_time', '>=', strtotime($time[0])];
            if (!empty($time[1])) $map[] = ['create_time', '<=', strtotime($time[1])];
        }
        if (!empty($tagName)) $map[] = ['tag_name', 'like', "%{$tagName}%"];
        if (!empty($tagType)) $map[] = ['tag_type', '=', $tagType];
        if (!empty($createUser)) $map[] = ['create_user', '=', $createUser];

        //权限过滤 根据人获取激活买家管理对应的asin
        $asinList = CommonService::asinAuth();
        if (!empty($asinList)) $map[] = ['asin', 'in', $asinList];

        $offset = ($page_size - 1) * $limit;
        $list = $this->model->getList($map, [[$sort, $order]],"{$offset},{$limit}");
        $count = $this->model->where($map)->count();

        return array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );

    }


    public function getEvaluationMonitoringConfig()
    {
        $config = [];
        $OrderAndCustomersOrderService = new OrderAndCustomersOrderService();
        $config['country_list'] = $OrderAndCustomersOrderService->country;
        //获取产品对应的asin和国家
        $config['asin_country_list'] = RedisService::getAsinAndCountry();
        //获取星级等级
        $ActivateService = new ActivateService();
        $config['star_rating_list'] = $ActivateService->starRatingRetention;

        return message("操作成功", true, $config);
    }

    public function getTagManageConfig()
    {
        $config = [];
        $config['tag_type'] = $this->tagType;
        //获取用户信息
        $UserModel = new UserModel();
        $userData = $UserModel->where('status', '=', 1)->get(['id', 'realname'])->toArray();
        $config['user_list'] = $userData;

        return message("保存成功", true, $config);

    }


    public function detail()
    {
        $param = request()->all();
        // 查询条件
        $map = [];
        $id = getter($param, 'id', 0);
        $time = getter($param, 'time', '');
        $title = getter($param, 'title', '');
        $stars = getter($param, 'stars', 0);
        $sort = getter($param, 'sort', 'id');
        $order = getter($param, 'order', 'desc');
        $page_size = getter($param, 'page', 1);
        $limit = getter($param, 'limit', 10);
        $map[] = ['mark','=',1];
        if (!empty($time)) $map[] = ['evaluation_time', '=', date("Y-m-d",strtotime($time))];
        if (!empty($id)) $map[] = ['evaluation_monitor_id', '=', $id];
        if (!empty($title)) $map[] = ['evaluation_title', 'like', "%{$title}%"];
        if (!empty($country)) $map[] = ['country', '=', $country];
        if (!empty($stars)) $map[] = ['stars', '=', $stars];

        $EvaluationMonitorConnectModel = new EvaluationMonitorConnectModel();
        $offset = ($page_size - 1) * $limit;

        $sql = "SELECT * FROM xs_evaluation.xs_evaluation_monitor_connect WHERE 1=1";

        $evaluationTime='';
        if (!empty($time)){
            $evaluationTime = date("Y-m-d",strtotime($time));
            $evaluationTimeExp = explode('-',$evaluationTime);
            $evaluationTimeExp[1] = intval($evaluationTimeExp[1]);
            $evaluationTime = $evaluationTimeExp[0].'-'.$evaluationTimeExp[1].'-'.$evaluationTimeExp[2];
        }

        if (!empty($evaluationTime)) $sql.=" AND evaluation_time='{$evaluationTime}'";
        if (!empty($id)) $sql.=" AND evaluation_monitor_id=".$id;
        if (!empty($stars)) $sql.=" AND stars=".$stars;
        if (!empty($title)) $sql.=" AND evaluation_title like"."%{$title}%";
        $sql.=" ORDER BY DATE(`evaluation_time`) desc";
        $count = DB::select($sql);
        
        $sql.=" limit {$limit} offset {$offset}";

        $list = DB::select($sql);
        $list = json_decode(json_encode($list), true);

//        $list = $EvaluationMonitorConnectModel->getList($map, [[$sort, $order]],"{$offset},{$limit}");
//        $count = $EvaluationMonitorConnectModel->where($map)
//            ->count();

        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => count($count),
        );

        return $message;
    }


    /**
     * @Notes:添加或编辑
     * @Interface edit
     * @return array|void
     * @author: wuyu
     * @Time: 2023/5/8   16:45
     */
    public function edit()
    {
        try {
            $params = request()->all();
            $productAsin = $params['product_asin'] ?? '';
            if (empty($productAsin)){
                throw new \Exception('参数错误');
            }
            $productAsinArr = explode('-',$productAsin);
            $countryName = $productAsinArr[0] ?? '';
            $asin = $productAsinArr[1] ?? '';
            $country = (new OrderAndCustomersOrderService())->country;
            $asin_country = '';

            foreach ($country as $key=>$val){
                if (strpos($countryName, $val) !== false) {
                    $asin_country = $key;
                    break;
                }
            }
            $data = [
                'country'=>$asin_country,
                'asin'=>$asin,
                'create_time'=>time(),
                'update_time'=>time()
            ];
            $exists = $this->model->where('country', '=', $asin_country)->where('asin', '=', $asin)->where('mark', '=', 1)->count();
            if ($exists > 0) throw new \Exception('评价监控已存在,请勿重复添加');
            $insertId = $this->model->insertGetId($data);
            if (empty($insertId)) throw new \Exception('操作失败');
            return message("保存成功", true, []);

        } catch (\Exception $e) {
            return message("保存失败:" . $e->getMessage(), false, []);
        }
    }


    public function status()
    {

        $params = request()->all();

        $id = $params['id'] ?? 0;
        $status = $params['status'] ?? 0;
        if (empty($id) || empty($status)) {
            return message("参数不存在", false, []);
        }
        $data = ['status' => $status];
        $this->model->where('id', $id)->update($data);
        $this->model->cacheReset($id, $data, $id);
        return message("操作成功", true, []);
    }


    /**
     * @Notes:导入产品asin对应的评论
     * @Interface importAsinComment
     * @author: wuyu
     * @Time: 2023/6/17   14:32
     */
    public function importAsinComment()
    {

    }



}
